<?php

namespace app\common\model;

use think\Env;
use think\Model;

/**
 * 模型
 */
class Goods extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    const STATUS_OK = 1;
    const STATUS_NO = 0;
    static $statusMap = [
        self::STATUS_OK => '上架',
        self::STATUS_NO => '下架',
    ];

    const DELETE_YES = 1;
    const DELETE_NO = 0;
    static $deleteMap = [
        self::DELETE_YES => '已删除',
        self::DELETE_NO => '未删除',
    ];

    public function shopGoods()
    {
        return $this->belongsTo('shopGoods', 'id', 'goods_id', [], 'LEFT')->setEagerlyType(0);
    }

    public function goodsImages()
    {
        return $this->hasMany(GoodsImage::class, 'goods_id');
    }

    // 追加属性
    protected $append = [

    ];

    public function setCoverImgAttr($value)
    {
        if (!empty($value)){
            $arr = parse_url($value);
            return $arr['path'];
        }
        return '';
    }


    public function getCoverImgAttr($value)
    {
        return !empty($value) ? Env::get('app.app_host') . $value : '';
    }

    public function getNoteAttr($value)
    {
        return $value ?? '';
    }


    public function clearImages($id)
    {
        return GoodsImage::where('goods_id', $id) ->delete();
    }

    /**
     * 批量获取产品信息
     * @param array $ids
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getGoodsByIds(array $ids)
    {
        return self::whereIn('id', $ids)->where('goods_status', self::STATUS_OK)->select();
    }

    /**
     * 获取产品信息
     * @param int $id
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getGoodsById(int $id)
    {
        return self::where([
            'id' => $id,
            'goods_status' => self::STATUS_OK,
        ])->find();
    }

}
